<template>
  <div>
<!--  查询表单-->
  <el-form :inline="true" :model="productObj" class="demo-form-inline">
    <el-form-item label="商品名称">
      <el-input v-model="productObj.search_name" placeholder="商品名称"></el-input>
    </el-form-item>
    <el-form-item label="商品类型">
      <div class="block">
        <el-cascader
            v-model="productObj.search_typeId"
            :options="typeOptions"
            @change="handleChange"></el-cascader>
      </div>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="success" @click="onSubmit">添加商品</el-button>
    </el-form-item>
  </el-form>

  <el-table
      :data="productAry"
      style="width: 100%">
    <el-table-column
        prop="productId"
        label="商品id"
        width="100">
    </el-table-column>
    <el-table-column
        prop="name"
        label="商品名称"
        width="150">
    </el-table-column>
    <el-table-column
        prop="price"
        label="商品价格(元)"
        width="150"
    >
    </el-table-column>
    <el-table-column
        prop="typeId"
        label="商品类型"
        width="100">
    </el-table-column>
    <el-table-column
        prop="imgLink"
        label="商品图片"
        width="150">
    </el-table-column>
    <el-table-column
        prop="stock"
        label="上架库存"
        width="150">
    </el-table-column>
    <el-table-column
        label="是否上架"
        prop="onOff">
      <template slot-scope="scope">
        <el-button
            size="mini"
            type="danger"
            v-if="scope.row.onOff=='1'"
            @click="setOnOff(scope.row.productId)"
        >下架</el-button>
        <el-button
            size="mini"
            type="success"
            v-else
            @click="setUpOff(scope.row.productId)"
        >上架</el-button>
      </template>
    </el-table-column>
<!--    <el-table-column-->
<!--        label="是否删除"-->
<!--        prop="status">-->
<!--      <template slot-scope="scope">-->
<!--        <span v-if="scope.row.status=='C001-1'">未删除</span>-->
<!--        <span v-else>已删除</span>-->
<!--      </template>-->
<!--    </el-table-column>-->
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
            size="mini"
            type="warning"
            @click="queryById(scope.row.productId) "
            >修改</el-button>
        <el-button
            size="mini"
            type="danger"
            @click="deleteById(scope.row.productId) "
        >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    <el-dialog
        title="添加商品"
        :visible.sync="displayProduct"
        width="30%">
      <el-form  label-width="80px" :model="addProduct">
        <el-form-item label="商品名称">
          <el-input v-model="addProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="addProduct.price"></el-input>
        </el-form-item>
        <el-form-item label="商品类型">
          <div class="block">
            <el-cascader
                v-model="addProduct.typeId"
                :options="typeOptions"
                @change="handleChange"></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/community/product/myupload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="displayProduct = false">取 消</el-button>
    <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
        title="修改商品信息"
        :visible.sync="dialogVisible"
        width="30%">
      <el-form  label-width="80px" :model="productList">
        <el-form-item label="商品名称">
          <el-input v-model="productList.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="productList.price"></el-input>
        </el-form-item>
        <el-form-item label="商品类型">
          <div class="block">
            <el-cascader
                v-model="productList.typeId"
                :options="typeOptions"
                @change="handleChange"></el-cascader>
          </div>
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8888/community/product/myupload"
              :show-file-list="false"
              :on-success="handleUpdateSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageLink" :src="imageLink" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="update">确 定</el-button>
      </span>
    </el-dialog>

<!--  分页工具-->
  <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
  </el-pagination>

  </div>
</template>

<script>
export default {
  data() {
    return {
      //当前页号
      currentPage: 1,
      //总记录数
      total: 0,
      //当前页大小
      pageSize: 5,
      //页大小列表
      pageSizes: [2, 5, 10, 20],
      //查询条件
      productObj: {},
      //商品数组
      productAry: [],
      //根据id查询要修改的商品对象
      productList: {},
      //添加商品上传图片路径
      imageUrl: '',
      //修改商品页面默认隐藏
      dialogVisible: false,
      //添加商品页面默认隐藏
      displayProduct: false,
      //定义一个从后端查询数据的级联选项
      typeOptions: [],
      //添加商品对象
      addProduct: {},
      //修该商品上传路径
      imageLink: ''
    }
  },
  methods: {
    //添加商品信息的头像上传的回调
    handleAvatarSuccess(res, file) {
      this.imageUrl = res;
      // console.log(1111,res)
      //将回调函数赋值给添加商品页面的文件上传
      this.addProduct.imgLink = this.imageUrl;

    },
    //修改商品信息的头像上传的回调
    handleUpdateSuccess(res, file) {
      this.imageLink = res;
      //将回调函数赋值给修改商品页面的文件上传
      this.productList.imgLink = this.imageLink
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt10M) {
        this.$message.error('上传头像图片大小不能超过 10MB!');
      }
      return isJPG && isLt10M;
    },
    handleChange() {
      console.log(this.productObj);
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1; // 重置当前页码为第1页
      this.getProduct()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getProduct()
    },
     async getProduct(){

      if (this.productObj.search_typeId!=null){
        const search_typeId=this.productObj.search_typeId.join('-')
        // console.log(search_typeId)
        this.productObj.search_typeId=search_typeId
      }
       console.log(this.productObj)
      //发送异步请求的post方法
      //带条件分页查询所有
      const {data:res}=
          await this.$http.post(`/community/product/list?pageNo=`+this.currentPage+`&pageSize=`+this.pageSize,this.productObj)
       console.log("sdfasdf ",res)
      this.productAry = res.rows
      this.total = res.total
    },
    search(){
      this.currentPage=1
      this.getProduct()
    },
    //下架库存
    async setOnOff(id){
      const pid=id
      // console.log(pid)
      const {data:res}=
          await this.$http.post(`/community/product/updateOnOff?id=`+pid)
      alert("下架成功!")
         console.log(res)
      this.search()
    },
    //上架库存
    setUpOff(id){
      const pid=id
      // console.log(pid)
      this.$prompt('请输入商品上架库存', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async ({ value }) => {

        const stock = value
        const res=
         await this.$http.post(`/community/product/updateUpOff?id=`+pid+`&stock=`+stock)
          this.search()

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消上架'
        });
      });
    },
    //根据id查询要修改的商品弹出面板信息
     async queryById(id){
      this.dialogVisible = true
      const pid=id
       const {data:res}=
           await this.$http.post(`/community/product/queryById?id=`+pid)
       // console.log(res)
       this.productList=res
    },

      //修改商品信息
    update(){
      // console.log(this.productList)
        this.dialogVisible = false
        this.$confirm('确定修改该商品信息吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {

          const typeId=this.productList.typeId.join('-')
          // console.log(search_typeId)
          this.productList.typeId = typeId
          console.log(this.productList)
          const {data:res}=
              await this.$http.post(`/community/product/updateById`,this.productList)
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.search()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          });
        });

      },

    //查询级联数据,商品类型表
    async fetchCascaderOptions(){
      const {data:res}=
          await this.$http.post(`/community/productType/list`)
      const typeOptions = []; // 初始化级联选项数组
      const map = {}; // 用于快速查找的映射
      // 遍历所有商品类型并构建映射
      res.forEach(item => {
        map[item.typeId] = { value: item.typeId,label: item.typeName, children: [] }; // 复制对象并添加 children 属性
      });
      // 遍历所有商品类型，并为其添加 children
      res.forEach(item => {
        if (item.parentId === null) {
          // 顶级商品类型，直接添加到 typeOptions
          typeOptions.push(map[item.typeId]);
        } else {
          // 子级商品类型，添加到其父级的 children 数组中
          map[item.parentId].children.push({value: item.typeId,label: item.typeName,});
        }
      });
      // 将最终的级联选项数组赋值给组件的 data 属性
      this.typeOptions = typeOptions;
      // console.log(this.typeOptions)
    },

    onSubmit(){
      this.displayProduct = true
      this.addProduct = {}
    },
    //添加新的商品
     add(){
      this.displayProduct = false
      this.$confirm('确定要添加该商品信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {

      const typeId=this.addProduct.typeId.join('-')
      this.addProduct.typeId = typeId
      // console.log(this.addProduct)
      const {data:res}=
          await this.$http.post(`/community/product/addProduct`,this.addProduct)
        this.$message({
          type: 'success',
          message: '添加成功!'
        });
      // console.log(res)
      this.search()
    }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加'
            });
      });
     },
    //删除商品(将商品status是否删除状态改为已删除)
    async deleteById(id){
      // console.log(id)
      this.$confirm('确定删除该商品信息吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const {data:res}=
            await this.$http.post(`/community/product/deleteById?id=`+id)
        this.$message({
          type: 'danger',
          message: '删除成功!'
        });
        this.search()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    }
  },
  mounted() {
    // 在组件加载时获取级联选项
    this.fetchCascaderOptions()
  }
}

</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

</style>